﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Transition : MonoBehaviour {

	static Transition instance;
	public static Transition Instance
	{
		get
		{
			if(instance == null)
				instance = GameObject.FindObjectOfType(typeof(Transition)) as Transition;
			return instance;
		}
	}

	public static bool allowTransition = false;
	public static bool levelLoaded = false;
	public static bool canPlayInterstitial = false;
	public static bool interstitialFinished = false;
	Animator animator;

	void OnEnable()
	{
		SceneManager.sceneLoaded += OnLevelLoaded;
	}

	void OnDisable()
	{
		SceneManager.sceneLoaded -= OnLevelLoaded;
	}

	void OnLevelLoaded(Scene scene, LoadSceneMode mode)
	{		
		if(allowTransition)
		{
			levelLoaded = true;
			if(interstitialFinished)
			{
				animator.Play("TransitionDeparting");
				interstitialFinished = false;
				levelLoaded = false;
			}
		}
			
	}

	void Awake ()
	{
		DontDestroyOnLoad(this.gameObject);
		animator = transform.GetChild(1).GetChild(0).GetComponent<Animator>();
	}

	public void PlayTransition()
	{		
		#if UNITY_EDITOR
		interstitialFinished = true;
		#endif
		transform.GetChild(1).gameObject.SetActive(true);
		animator.Play("TransitionArriving");
	}

	public void PlayTransitionWithoutInterstitial()
	{		
		canPlayInterstitial = false;
		interstitialFinished = true;
		transform.GetChild(1).gameObject.SetActive(true);
		animator.Play("TransitionArriving");
	}	

	public void CheckTransitionRemoval()
	{
		if(allowTransition)
		{
			interstitialFinished = true;
			if(levelLoaded)
			{
				animator.Play("TransitionDeparting");
				interstitialFinished = false;
				levelLoaded = false;
			}
		}
	}
}
